package com.example.sax;

import android.app.Person;
import android.text.TextUtils;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class XMLUtil
{
    public static List<Bean> parsBeanList(InputStream inputStream) throws XmlPullParserException, IOException {
        //
        XmlPullParser xmlPullParser = XmlPullParserFactory.newInstance().newPullParser();

        List<Bean> beanList = null;
        Bean person = null;

        xmlPullParser.setInput(inputStream,"UTF-8");

        int eventType = xmlPullParser.getEventType();

        while (eventType != XmlPullParser.END_DOCUMENT)
        {
            switch (eventType)
            {
                case XmlPullParser.START_DOCUMENT:
                    beanList = new ArrayList<>();
                    break;
                case XmlPullParser.START_TAG:
                    switch (xmlPullParser.getName())
                    {
                        case "person":
                            person = new Bean();
                            person.setId(xmlPullParser.getAttributeValue(0));
                            break;
                        case "name":
                            if (null != person)
                            {
                                person.setName(xmlPullParser.nextText());
                            }
                            break;
                        case "age":
                            if (null != person)
                            {
                                person.setAge(xmlPullParser.nextText());
                            }
                            break;

                    }
                    break;
                    case XmlPullParser.END_TAG:
                        if ("person".equals(xmlPullParser.getName()))
                        {
                            beanList.add(person);
                            person = null;
                        }
                        break;
            }
            //轮动解析，如果while循环最后没有修改eventType，则会死循环
            eventType = xmlPullParser.next();
        }
        return beanList;
    }
}
